﻿using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace yMethod
{
    public class FileHelp
    {
        /// <summary>
        /// 将xml文件中转换为特定实例对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <returns></returns>
        private static T ReadXmlFile<T>(string path) where T : class
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            StreamReader reader = null;
            try
            {
                reader = new StreamReader(path, Encoding.Default);
                return (T)(serializer.Deserialize(reader));
            }
            catch
            {
                return default;
            }
            finally
            {
                reader?.Close();
            }
        }
        /// <summary>
        /// 将特定对象写入xml文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <param name="xmlObj"></param>
        /// <returns></returns>
        public static bool WriteXmlFile<T>(string path, T obj) where T : class
        {
            try
            {
                string dir = Directory.GetParent(path).FullName;
                if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
                if (!File.Exists(path)) File.Create(path).Close();
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                using (StreamWriter sw = new StreamWriter(path, false, Encoding.Default))
                {
                    serializer.Serialize(sw, obj);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
